#include "GetGameList.hh"
#include "GameList.hh"
#include "XmlServerThread.hh"
#include "XmlSocket.hh"
#include "../World/Galaxy.hh"
#include "../Exception.hh"

using namespace Network;
using namespace World;


spGetGameList GetGameList::construct(QDomElement const& message) {
    DONTCARE(message);
    return spGetGameList(new GetGameList());
}

void GetGameList::process_on_server(XmlServerThread& thread) {
    if (thread.get_state() != AUTH_OK)
        throw NonFatalProtocolError("init unexpected");

    Galaxy::GalaxyMap galaxies = Galaxy::get_galaxies();
    GameList::GameListInfo gameListInfo;

    for (
      Galaxy::GalaxyMap::iterator i = galaxies.begin();
      i != galaxies.end();
      ++i
    ) {
        Galaxy::PlayerMap players = i.value()->get_players();
        GameList::PlayerListInfo playerListInfo;

        for (
          Galaxy::PlayerMap::iterator j = players.begin();
          j != players.end();
          ++j
        ) {
            playerListInfo.insert(j.value()->get_user()->get_name());
        }

        GameList::GameInfo gameInfo;
        gameInfo.minPlayers = i.value()->minPlayers;
        gameInfo.maxPlayers = i.value()->maxPlayers;
        gameInfo.playerListInfo = playerListInfo;
        gameListInfo.insert(i.key(), gameInfo);
    }

    GameList gameList(gameListInfo);
    gameList.send_to(*thread.get_socket());
}

QDomDocument GetGameList::to_xml() const {
    QDomDocument doc;
    QDomElement init = doc.createElement("init");
    QDomElement getGameList = doc.createElement("get_game_list");
    doc.appendChild(init);
    init.appendChild(getGameList);
    return doc;
}
